//
//  imagePickViewController.m
//  Collection
//
//  Created by satya on 10/12/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "imagePickViewController.h"
#import "PreviewController.h"
#import "SignatureVC.h"
#import "AddNewCarSectionViewController.h"
#import "dbFunctions.h"
#import "OneSectionDetailController.h"

@implementation imagePickViewController
@synthesize imgPick,arrDbDetails,imgPicker,arrImgName,carSectionBtn,dic;

// The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
/*
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization.
    }
    return self;
}
*/


// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
	
	//self.title = @"";
	
	
   
    //arrImages= [db getCarSectionDetails];
   
	UISegmentedControl *control = [[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:@"Add Section",@"Next",nil]];
	control.segmentedControlStyle = UISegmentedControlStyleBar;
	control.momentary = YES;
	[control addTarget:self action:@selector(segmentValueChanged:) forControlEvents:UIControlEventValueChanged];			
	UIBarButtonItem *controlItem = [[UIBarButtonItem alloc] initWithCustomView:control];
	self.navigationItem.rightBarButtonItem = controlItem;
	[control release];
	[controlItem release];
	
	carSectionBtn = [[NSMutableArray alloc]initWithObjects:@"",nil];
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
	}

-(void) segmentValueChanged:(id) sender{
    UISegmentedControl *segmentCtrl = (UISegmentedControl *)sender;
	if(segmentCtrl.selectedSegmentIndex == 0){
		/*PreviewController *carSec = [[PreviewController alloc]initWithImages:arrImages andImagesName:arrImgName];
		[self.navigationController pushViewController:carSec animated:YES];
		[carSec release];*/
        AddNewCarSectionViewController *objCarSectionController = [[AddNewCarSectionViewController alloc] init];
        objCarSectionController.sender = self;
        objCarSectionController.selector = @selector(signatureDismiss);
        [self presentModalViewController:objCarSectionController animated:YES];
        [objCarSectionController release]; 
        
	}
	
	if(segmentCtrl.selectedSegmentIndex == 1){
		SignatureVC *carSec = [[SignatureVC alloc]init];
		//carSec.sender = self;
		//carSec.selector = @selector(signatureDismiss);
		//[self presentModalViewController:carSec animated:YES];
		[self.navigationController pushViewController:carSec animated:YES];
		[carSec release];
	}
	
}

-(void)signatureDismiss{
	
	[self dismissModalViewControllerAnimated:YES];
    
    dbFunctions *db = [[dbFunctions alloc]init];
    
    arrDbDetails = [[db getCarSectionDetails] copy];
    NSLog(@"%@",arrDbDetails);
    
    [imgPick reloadData];
    [db release];

}







#pragma mark -
#pragma mark Table view data source


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    if (arrDbDetails == nil)
        return 0;
    else
	return [arrDbDetails count];
}



// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
	}
    
    // Configure the cell...
    NSUInteger row = [indexPath row];
  
    if (arrDbDetails == nil)
    {
    }
       
        else{
    
    //NSLog(@"arrImages counting %@",[arrDbDetails objectAtIndex:row]);

    dic = (NSMutableDictionary*)[arrDbDetails objectAtIndex:row];
    
    UILabel *sectionImg = [[UILabel alloc]init];
            [sectionImg setText:@"section image"];
            sectionImg.font = [UIFont systemFontOfSize:12];
            [sectionImg setTextColor:[UIColor grayColor]];
            sectionImg.frame = CGRectMake(3 , 72, 130, 20);
            
            UILabel *sectionname = [[UILabel alloc]init];
            [sectionname setText:@"section name"];
            sectionname.font = [UIFont systemFontOfSize:12];
            [sectionname setTextColor:[UIColor grayColor]];
            sectionname.frame = CGRectMake(160 , 72, 130, 20);        

    UILabel *btnItem = [[UILabel alloc]init];
	
	[btnItem setText:[dic objectForKey:@"carsection"]];
    [btnItem setTextColor:[UIColor blackColor] ];
    [btnItem setNumberOfLines:2];
	btnItem.frame = CGRectMake(158, 20, 150, 40);


	//[btnItem addTarget:self action:@selector(selectItem:) forControlEvents:UIControlEventTouchUpInside];
	
    NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *pngFilePath = [NSString stringWithFormat:@"%@/%@",docDir,[dic valueForKey:@"carsection"]];
    NSData *imgdata = [NSData dataWithContentsOfFile:pngFilePath];
    NSLog(@"Dic Value %@ and %drow value",dic,indexPath.row);
	UIImage * img = [UIImage imageWithData:imgdata];
    
	NSLog(@"Image %@",img);

	UIButton *btnPickImage = [UIButton buttonWithType:UIButtonTypeCustom];
	//[btnPickImage setBackgroundImage:(UIImage*)[(NSDictionary*)[arrImages objectAtIndex:indexPath.row] objectForKey:@"pic"] forState:UIControlStateNormal];
	[btnPickImage setBackgroundImage:img forState:UIControlStateNormal];
	btnPickImage.frame = CGRectMake(0, 6, 130, 70); 
	//[btnPickImage addTarget:self action:@selector(changeImageBackground:) forControlEvents:UIControlEventTouchUpInside];
	btnPickImage.tag = indexPath.row;

	//[btnItem addTarget:self action:@selector(selectImage:) forControlEvents:UIControlEventTouchUpInside];
	[cell.contentView addSubview:btnItem];
	[cell.contentView addSubview:btnPickImage];
            [cell.contentView addSubview:sectionImg];
            [cell.contentView addSubview:sectionname];
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            [sectionname release];
            [sectionImg release];
            [btnItem release];

        }	
	
	
    return cell;
}

/*
NSInteger itemNum;
-(void)changeImageBackground:(UIButton*)btnSender {
	itemNum = btnSender.tag;
	
	//imgPicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
	//[self presentModalViewController:imgPicker animated:YES];
	
	UIActionSheet *actiosheet = [[UIActionSheet alloc]initWithTitle:@"SELECT" delegate:self cancelButtonTitle:nil destructiveButtonTitle:@"Cancel" otherButtonTitles:@"Take New Picture",@"Go To Photo Album",nil];
	actiosheet.actionSheetStyle = UIActionSheetStyleBlackOpaque;
	
	[actiosheet showInView:imgPick];
	[actiosheet release];
}

-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
	imgPicker = [[UIImagePickerController alloc] init];
	imgPicker.delegate = self;
	if (buttonIndex == 1) {
		//self.label.text = @"Other Button 1 Clicked";
		if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
			imgPicker.sourceType = UIImagePickerControllerSourceTypeCamera;
			[self presentModalViewController:imgPicker animated:YES];
		}
		else {
			UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Alert" message:@"Currently, Your device does not support camera. " delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil];
			alert.opaque = YES;
			[alert show];
			[alert release];
		}
		
	} 
	else if (buttonIndex == 2) {
		//self.label.text = @"Other Button 2 Clicked";
		imgPicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
		[self presentModalViewController:imgPicker animated:YES];
	}
}


- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {

	//UIImage *image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
	UIImage *im=[info objectForKey:@"UIImagePickerControllerOriginalImage"];
	UIGraphicsBeginImageContext( CGSizeMake(im.size.width/4 ,im.size.height/4) );
	[[info objectForKey:@"UIImagePickerControllerOriginalImage"] drawInRect:CGRectMake(0,0,im.size.width/4 ,im.size.height/4)];
	UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
	UIGraphicsEndImageContext();
	
	NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
	NSString *pngFilePath = [NSString stringWithFormat:@"%@/%@",docDir,[arrImgName objectAtIndex:itemNum]];
	NSLog(@"...... %@",pngFilePath);
	NSData *imgData = [NSData dataWithData:UIImageJPEGRepresentation(img, 0.0)];
	
	[imgData writeToFile:pngFilePath atomically:YES];
    NSMutableDictionary *dictPhoto = [[NSMutableDictionary alloc]init];
	NSLog(@"Array Images%@",arrImages);
 
	 //dictPhoto = (NSMutableDictionary*)[arrImages objectAtIndex:itemNum];
	[dictPhoto setObject:img forKey:@"pic"];
	[arrImages replaceObjectAtIndex:itemNum withObject:dictPhoto];
	NSLog(@"Array Images%@",arrImages);
	[dictPhoto release];
	
	
	//}
	/*UIImage *image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
	 NSString *headerName = [[NSString alloc] init];
	 headerName = [NSString stringWithFormat:@"%@%d.png",imgtitle,arrPhotoList.count];
	 
	 NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
	 NSString *pngFilePath = [[NSString stringWithFormat:@"%@/images/%@/",docDir,imgtitle] stringByAppendingFormat:@"%@",headerName];
	 //NSString *pngFilePath = [NSString stringWithFormat:@"%@/%@",docDir,headerName];
	 NSLog(@"%@",pngFilePath);
	 NSData *imgData = [NSData dataWithData:UIImageJPEGRepresentation(image, 0.0)];
	 [imgData writeToFile:pngFilePath atomically:YES];
	 [picker dismissModalViewControllerAnimated:YES];
	 [imgPick reloadData];
}



-(void)selectItem:(id)sender
{
	
	//[self.tableView setEditing:!self.tableView.editing animated:YES];
//    if (imgPick.editing) {
		[imgPick setEditing:NO animated:YES];
	//} 
	//else
	//[imgPick setEditing:YES animated:YES];
	
	
	 NSMutableDictionary *dictPhoto = [[NSMutableDictionary alloc]init];
	 [dictPhoto setObject:[UIImage imageNamed:@"PickPhoto.jpg"] forKey:@"pic"];
	 [arrImages addObject:dictPhoto];
	 [dictPhoto release];
	[self performSelector:@selector(reloadTable) withObject:nil afterDelay:0.3];

	
	
	//[imgPick setEditing:YES];
    //[imgPick insertRowsAtIndexPaths:<#(NSArray *)indexPaths#> withRowAnimation:<#(UITableViewRowAnimation)animation#>


}
-(void)reloadTable{
	[imgPick reloadData];

}
 
 
 */

#pragma mark -
#pragma mark Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // Navigation logic may go here. Create and push another view controller.
    
    dic = (NSMutableDictionary*)[arrDbDetails objectAtIndex:indexPath.row];

    OneSectionDetailController *detailViewController = [[OneSectionDetailController alloc] initWithDetails:dic];
	 // ...
	 // Pass the selected object to the new view controller.
	 [self.navigationController pushViewController:detailViewController animated:YES];
	 [detailViewController release];
	 
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
	return 92;
	
}


/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations.
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

-(void)viewWillAppear:(BOOL)animated
{
    
    [self signatureDismiss];
	[super viewWillAppear:YES];


}

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc. that aren't in use.
}

- (void)viewDidUnload {
    [super viewDidUnload];
	//imgPick = nil;
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}


- (void)dealloc {
    [super dealloc];
	[arrDbDetails release];
	[imgPick release];
	[imgPicker release];
	[arrImgName release];
	[carSectionBtn release];
}


@end
